package com.anda.jsu.yangsp.core.service;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.anda.jsu.yangsp.core.persistence.IBasicDao;
import com.anda.jsu.yangsp.core.view.util.PageModel;

/**
 * 
 * @author xiaolu
 * @since 2012-12-06
 *
 */
@Service("basicService")
public class BasicServiceImpl<T> implements IBasicService<T> {

	@Autowired
	IBasicDao<T> basicDao;
	
	/**
	 * 得到子类的实体对象
	 */
	protected Class<T> entityClass = getEntityClass();
	private String entityName;
	
	public void delete(T t) {
		basicDao.delete(t);
	}

	/**
	 * 得到实体类的名称
	 */
	public Class<T> getEntityClass() {
		//得到运行期的父类
		Type parentType = this.getClass().getGenericSuperclass();
		//判断该类是否为泛型类
		if(parentType instanceof ParameterizedType){
			ParameterizedType type = (ParameterizedType) parentType;
			//得到泛型中的参数
			Class<T> entityClazz = (Class<T>) type.getActualTypeArguments()[0];
			entityName = entityClazz.getSimpleName();
			return entityClazz;
		}
		return null;
	}

	public void deleteAll(List<T> entities) {
		basicDao.deleteAll(entities);
	}

	public T findById(Serializable entityId) {
		return basicDao.selectById(entityClass, entityId);
	}

	public void save(T t) {
		basicDao.save(t);
	}

	public void saveOrUpdate(T t) {
		basicDao.saveOrUpdate(t);
	}

	public void update(T t) {
		basicDao.update(t);
	}

	public List<T> list(PageModel<T> view) {
		return basicDao.list(view);
	}

}
